/*
*  <template slot="prefix" slot-scope="ref">
                    <a-button type="primary" icon="plus" @click="handleEdit(null,1)" v-btnPermission="'mm_004_add_01'">
                        新增
                    </a-button>
                </template>
* */
import { array } from 'js-md5'
import Vue from 'vue'
import VueDraggableResizable from 'vue-draggable-resizable'
Vue.component('vue-draggable-resizable', VueDraggableResizable)
import { get } from 'lodash'
import './index.less'
export default {
  name: 'ListTable',
  props: {
    ArrTableData: {
      type: Array,
    },
    //是否显示分页
    showPage: {
      type: Boolean,
      default() {
        return true
      }
    },
    //分页的配置项，请求数据是会依照这个来传参
    pageKeys: {
      type: Array,
      default() {
        return ['pageNo', 'pageSize', 'totalSize']
      }
    },
    //选择的配置项，默认关闭，type可选为checkbox或radio，多选或者单选
    //注意：exportConfig.use为ture的话，会自动将selectConfig设置为{use: true, type: 'checkbox' }
    //如果点击事件没生效，那肯定是rowKey没设置对

    // :selectConfig = "{use: true, type: 'radio',rowKey: 'id' }"
    selectConfig: {
      type: Object,
      default() {
        return {
          use: false, //是否使用，传false不会显示选择栏
          type: 'checkbox', //checkbox或radio，多选或者单选
          rowKey: 'id'
        }
      }
    },
    //同a-table的columns，主要作用：div上不再显示[object Object],[object Object]...这种东西；次要作用：传值到a-table
    columns: {
      type: Array,
      required: true
    },
    //导出配置选择
    //:exportConfig="{ use: true,select: '导出选中',all: '导出全部'}"
    exportConfig: {
      type: Object,
      default() {
        return {
          use: false, //是否导出，传false不会显示操作栏
          select: '导出选中', //导出选中的文件名
          all: '导出全部', //导出全部的文件名
          customColumns: null, //需要导出的表头,
          monitorColums: false //是否需要监听表头变化,
        }
      }
    },
    //导出配置文字选择
    //:exportConfigText="{ select: '导出选中',all: '导出全部'}"
    exportConfigText: {
      type: Object,
      default() {
        return {
          select: '导出选中', //导出选中的文件名
          all: '导出全部' //导出全部的文件名
        }
      }
    },
    //导出权限配置选择
    //:exportPermission="{select: 'asdfa',all: 'asdfa'}"
    exportPermission: {
      type: Object,
      default() {
        return null
      }
    },
    //分页配置
    pageSizeOptions: {
      type: Array,
      default() {
        return ['10', '20', '30', '40', '100']
      }
    },
    /*
    如果不处理返回数据直接return 接口就可以了，如：parameter => getMonthlyReportList(Object.assign(parameter, this.queryParam))
    下面是要处理参数，然后还要包装返回数据的，有些后端瞎鸡儿返回的
    loadData: async parameter => {
        if (this.queryParam.createdTime && this.queryParam.createdTime.length > 0) {
          this.queryParam.evaluateStartTime = this.queryParam.createdTime[0].format('YYYY-MM-DD')
          this.queryParam.evaluateEndTime = this.queryParam.createdTime[1].format('YYYY-MM-DD')
          delete this.queryParam.createdTime
        }
        // this.getMonthlyReportsTotalReq()
        const requestParameters = Object.assign({}, parameter, this.queryParam)
        let res = await getMonthlyReportList({}, requestParameters)
        if (res.code === this.SUCCESS_CODE) {
          return { code: 200, ...res.data, data: res.data.list }
        }
        return { code: 200, data: [] }
    },
    * */
    //数据请求方法，返回值应该是一个promise
    request: {
      type: Function,
      // required: true,
      default() {
        return () => { }
      }
    },
    //:statisticsConfig = "{use: true,statistics}"
    statisticsConfig: {
      type: Object,
      default() {
        return {
          use: false, //是否统计，传false不会显示操作栏
          statistics: null,
          temp: null
        }
      }
    },
    outLoading: {
      type: Boolean,
      default: false
    },
    outSelectedRowKeys: {
      type: Array,
      default() {
        return []
      }
    },
    rowSelectionConfig: {
      type: Object,
      default() {
        return {}
      }
    },
    disabledLoading: {
      type: Boolean,
      default() {
        return false
      }
    },
    delFunc: {
      type: [Object, Function],
      default() {
        return null
      }
    },
    disabled: {
      type: Boolean,
      default() {
        return false
      }
    },
    transformTimeKey: {
      type: Array,
      default() {
        return []
      }
    },
    // 从表格第几列开始导出
    startIndex: {
      type: [Number, String],
      default() {
        return 1
      }
    },
    // 数据过滤器
    filterData: {
      type: Function,
      default() {
        return null
      }
    },
    isShowCountBar: {
      type: Boolean,
      default() {
        return null
      }
    },
    isShowTotal: {
      type: Boolean,
      default() {
        return true
      }
    },
    isShowTotalName: {
      type: String,
      default() {
        return '总计'
      }
    },
    isShowDeleteCount: {
      type: Boolean,
      default() {
        return true
      }
    },
    size: {
      type: String,
      default: 'small'
    },
    isScrollX: {
      type: [Number, Boolean],
      default() {
        return true
      }
    },
    isScrollY: {
      type: [Number, Boolean],
      default() {
        return false
      }
    },
    isDrag: {   //是否要拖拽，有些复杂的table，拖拽有问题
      type: Boolean,
      default() {
        return true
      }
    },
    isEmptyWidth: {   //是否要去除宽度，
      type: Boolean,
      default() {
        return false
      }
    },
    isFixedRight: {
      type: Boolean,
      default() {
        return true
      }
    },
    isEportIndex: {    //是否导出序列号
      type: Boolean,
      default() {
        return false
      },
    },
    isHideFixed: {   //没有固定列，加一个透明的固定列，用于列表自适应
      type: Boolean,
      default() {
        return false
      },
    },
    isInit: {
      type: Boolean,
      default: true
    },
    isShowColumnFilter: {
      type: Boolean,
      default: true
    },
    isShowTable: {
      type: Boolean,
      default: false
    },
  },
  /*
   向上发射的事件
  * emit:{
      //行点击事件，回传的参数是点击event,和行数据
      row-click(event, record)，
      //选中框的事件，回传的是已选中的所有行。和row-click可同时绑定
      select-click(records)，
  * }
  * */
  data() {
    // 拖拽核心代码
    this.components = {
      header: {
        cell: (h, props, children) => {
          const { key, ...restProps } = props;
          const col = this.columns.find((col) => {
            const k = col.dataIndex || col.key;
            return k === key;
          });

          if (!col || !col.width) {
            return h("th", { ...restProps }, [...children]);
          }

          const dragProps = {
            key: col.dataIndex || col.key,
            class: "table-draggable-handle",
            attrs: {
              w: 10,
              x: col.width,
              z: 1,
              axis: "x",
              draggable: true,
              resizable: false,
            },
            on: {
              dragging: (x, y) => {
                console.log(key, '宽', x, y)
                if (x != 0) {
                  col.width = Math.max(x, 100);
                }
              },
            },
          };
          const drag = h("vue-draggable-resizable", { ...dragProps });
          return h("th", { ...restProps, class: "resize-table-th" }, [
            ...children,
            drag,
          ]);
        },
      },
    };
    return {
      pathName: this.$route.path,
      innerLoading: false,
      loadingExport: false,
      //选中的key
      selectedRowKeys: [],
      pageNo: 1,
      pageSize: Number(this.pageSizeOptions[0]),
      totalSize: 0,
      tableData: [],
      selectedRowsMap: new Map(),
      // 初始备份的表格列配置描述及过滤后的容器
      filterColumn: [],
      isScroll: {},  // 设置横向滚动条
      indeterminate: false,//全选字段
      checkAll: true,//全选字段
      visible: false,//是否打开筛选
    }
  },
  created() {
    this.getColumns();
    if (!this.$route.params?.statisticsId && this.isInit) {  //表扬信管理模块bug修改
      this.getData()
    }
    this.isScroll.x = this.isScrollX;
    this.isScroll.y = this.isScrollY;
  },
  watch: {
    columns: {
      deep: true,
      handler(val) {
        if (val) {
          this.getColumns();
          if (this.exportConfig.use && this.exportConfig.monitorColums) {
            const columns = val // 需要导出的自定义表头，不存在则使用默认
            this.$refs.exportSelect.tableToExcelFile(columns ? { columns } : this.$refs.table, this.startIndex)
            this.$refs.exportAll.tableToExcelFile(columns ? { columns } : this.$refs.table, this.startIndex)
            this.selectConfig.use = true
            this.selectConfig.type = 'checkbox'
          }
        }
      }
    },
    outLoading() {
      this.innerLoading = this.outLoading
    },
    outSelectedRowKeys: {
      immediate: true,
      handler() {
        this.selectedRowKeys = this.outSelectedRowKeys
      }
    },
    selectedRowKeys(newVal) {
      this.$emit('update:outSelectedRowKeys', newVal)
    },

    //如果勾选了 没点确认 让复选框复原
    visible(newVal) {
      if (newVal === true) {
        let getsColumnData = JSON.parse(localStorage.getItem('dynamicColumn')) || [];
        let path = this.$route.path;
        let checked = getsColumnData.filter(item => {
          return item.path === path && item.name === this.request.name;
        })

        if (checked?.length > 0) {
          //动态获取存储的值
          checked[0].checkedData.forEach(item => {
            this.checkColumn.forEach(sub => {
              if (sub.value === item.value) {
                this.$set(sub, 'checked', item.checked)
              }
            })
          })
        } else {
          this.checkColumn = this.checkColumn.map(item => {
            this.$set(item, 'checked', true)
            return item
          });
        }
        let ischeckAll = this.checkColumn.some(item => {
          return !item.checked
        })
        this.checkAll = !ischeckAll
        this.indeterminate = ischeckAll ? true : false
      }
    }
  },
  computed: {
    // 用计算属性取出columns的dataIndex，作为多选框的选项数据
    checkColumn: {
      get() {
        let array = [];
        this.$props.columns.forEach(item => {
          array.push({
            value: item.title,
            checked: true,
            disabled: item.checkColumn
          })
        });
        array.forEach((item, index) => {
          if (item.value.trim() === '操作') {
            array.splice(index, 1)
          }
        })
        return array
      },
      set(val) { }
    },
  },
  methods: {
    //全选反选 动态列
    onCheckAllChange(e) {
      // console.log()
      // this.indeterminate = this.checkColumn.findIndex(el => el.checkColumn) > -1
      // this.checkAll = e.target.checked;
      if (e.target.checked) {
        this.indeterminate = false
      } else {
        if (this.checkColumn.findIndex(el => el.disabled) > -1) {
          this.indeterminate = true
        } else {
          this.indeterminate = false
        }
      }
      this.checkAll = e.target.checked;
      this.checkColumn = []
      this.checkColumn.forEach(item => {
        if (!item.disabled) {
          this.$set(item, 'checked', e.target.checked)
        }
      })
      this.$forceUpdate();
    },
    //改变列 动态列
    checkedChange(e, value) {
      this.checkColumn.forEach(item => {
        if (item.value === value) {
          this.$set(item, 'checked', e.target.checked)
        }
      })
      this.$forceUpdate();
      //是否全选判断
      let ischeckAll = this.checkColumn.every(item => {
        return item.checked
      })
      if (ischeckAll) {
        this.indeterminate = !ischeckAll
        this.checkAll = ischeckAll
      } else {
        this.indeterminate = this.checkColumn.some(item => item.checked)
        this.checkAll = ischeckAll
      }
    },

    // 根据条件设置column属性
    setColumnAttribute() {
      this.filterColumn = this.filterColumn.map(item => {
        // 单独设置序号的宽度
        if (item.title.includes('序号') && !item.customize) {
          item.width = 70;
          item.customCell = () => {
            return {
              style: {
                'width': '70px',
              }
            }
          }
        }
        if (item.title.includes('序号') && item.customize) {
          item.width = 110;
          item.customCell = () => {
            return {
              style: {
                'width': '110px',
              }
            }
          }
        }

        if (item.title.includes('操作')) {
          item.width = 170;
          item.customCell = () => {
            return {
              style: {
                'width': '170px',
              }
            }
          }
        }
        if (item.scopedSlots && item.scopedSlots.customRender === 'checkedslot') {
          item.width = 50;
          item.customCell = () => {
            return {
              style: {
                'width': '50px',
              }
            }
          }
        }
        if (!['序号', '操作'].includes(item.title)) {
          item.customCell = () => {
            return parseInt(item.width) < 120 ? {
              style: {
                'width': item.width,
                'max-width': '400px',
                'height': '52px'
              }
            } : {
              style: {
                'min-width': item.minWidth || '120px',
                'max-width': '400px',
                'height': '52px'
              }
            }
          }
        }


        // 判断是否有插槽，没有插槽文字长度超过添加换行及鼠标移入显示
        if (!item.scopedSlots && !item.customRender) {
          item.customRender = (text, record) => {
            // 解决dataIndex 多层级
            return <a-tooltip title={get(record, item.dataIndex)} ><span class="ellipsis-span">{get(record, item.dataIndex)}</span></a-tooltip>

          }
        }

        return item;
      })
    },
    //获取记录的动态列
    getColumns() {
      let getsColumnData = JSON.parse(localStorage.getItem('dynamicColumn')) || [];
      let path = this.$route.path;
      let checked = getsColumnData.filter(item => {
        return item.path === path && item.name === this.request.name;
      })
      if (checked?.length > 0) {
        //动态获取存储的值
        checked[0].checkedData.forEach(item => {
          this.checkColumn.forEach(sub => {
            if (sub.value === item.value) {
              sub.checked = item.checked
            }
          })
        })
        this.checkAll = checked[0].checkedData.every(item => {
          return item.checked
        })
        this.indeterminate = this.checkAll ? false : true
        this.checkChange();
      } else {
        this.filterColumn = this.$props.columns;
      }
      if (this.filterColumn?.length < 1) {
        return false
      }

      this.setColumnAttribute();

    },
    hide() {
      this.visible = false;
    },
    //动态列确定改变
    checkChange() {
      let isOneList = this.checkColumn.some(item => {
        return item.checked === true
      })
      if (!isOneList) {
        this.$message.warning('请至少选择一列')
        return false
      }
      let selectArr = []
      this.checkColumn.map(item => {
        selectArr.push({
          value: item.value,
          checked: item.checked
        })
      })
      // 初始是默认全选的，假设此刻点击了name的选择框
      let columns = this.$props.columns;
      let path = this.$route.path;
      let getsColumnData = JSON.parse(localStorage.getItem('dynamicColumn')) || [];
      let data = { path: path, checkedData: selectArr, name: this.request.name }
      let isHave = getsColumnData.some(item => {
        return item.path === path && item.name === this.request.name
      })
      if (!isHave) {
        getsColumnData.push(data)
      }
      getsColumnData = getsColumnData.map(item => {
        if (item.path === path && item.name === this.request.name) {
          item = data;
        }
        return item
      })
      localStorage.setItem('dynamicColumn', JSON.stringify(getsColumnData));
      // 核心部分，数组过滤循环遍历columns，如果选择的值中包含dataIndex则为true并暴露出去，反之亦然
      let check = selectArr.map(item => {
        if (item.checked) {
          return item.value
        }
      })
      const filterValue = columns.filter(item => {
        if (check.includes(item.title)) {
          // 当暴露值为true时，循环遍历的值会赋给filterValue
          return true
        }
        if (item.title.trim() === '操作') {
          return true
        }
        return false
      })
      // 依旧是假设点击的是name的选择框，暴露的值为[false,true,true,true],所以filterValue中的值没有包含name的那一列
      // 然后将值赋给filterColumns;
      this.filterColumn = filterValue;
      // setTimeout(() => {
      //   document.querySelector(".ant-popover").style.display = 'none'//确认关闭
      // }, 500);
      this.visible = false;
      this.setColumnAttribute();  // 点击时回调头部样式设置函数

      //是否加透明列
      let isKeyHideFixed = this.filterColumn.find((item) => item.dataIndex == 'isHideFixed');
      if (this.isHideFixed && !isKeyHideFixed) {
        this.filterColumn.push(
          { title: '', dataIndex: 'isHideFixed', fixed: 'right', },
        )
      }
    },
    /*
       * 删除方法，delFunc：对应的删除接口
       *
       * 使用例子：slot-scope="ref"里面的ref是回传的this对象，可以使用本组件methods里面的所有方法。
       *   <template :slot="state !== 3 ? 'prefix':''" slot-scope="ref">
               <a-button type="primary" @click="openDailog">添加行</a-button>
               <a-button @click="ref.delete(delFuc)">删除行</a-button>
           </template>
       * */
    delete(delFunc, callback) {
      if (delFunc) {
        this.$delList2(
          delFunc,
          async () => {
            if (this.totalSize - this.selectedRowKeys.length <= (this.pageNo - 1) * this.pageSize) {
              this.pageNo = this.pageNo - Math.round(this.selectedRowKeys.length / this.pageSize)
              this.pageNo = this.pageNo < 0 ? 0 : this.pageNo
            }
            // console.log(this.totalSize >= this.pageNo * this.pageSize)
            // console.log(this.pageNo)
            await this.getData()
            this.selectedRowKeys = []
            this.selectedRowsMap = new Map()
            callback && callback()
          },
          { ids: this.selectedRowKeys }
        )
      } else {
        this.$message.warning('请绑定删除方法')
      }
    },
    //notice:外部刷新数据，请这样使用getData(null , true)
    //notice:外部刷新数据，请这样使用getData(null , true)
    //notice:外部刷新数据，请这样使用getData(null , true)
    //notice:外部刷新数据，请这样使用getData(null , true)
    //notice:外部刷新数据，请这样使用getData(null , true)
    //notice:外部刷新数据，请这样使用getData(null , true)
    //notice:外部刷新数据，请这样使用getData(null , true)
    //notice:外部刷新数据，请这样使用getData(null , true)
    //获取数据
    async getData(callback, isReset = false, isClear = false, refresh = true) {
      // 虽然有点体验不好，但这是解决MoreBtn当前页不更新问题
      if (refresh) {
        this.tableData = []
      }
      isClear && this.clearSelected()
      let page = {}
      page[this.pageKeys[0]] = this.pageNo
      page[this.pageKeys[1]] = this.pageSize
      if (callback) {
        page[this.pageKeys[0]] = 1
        page[this.pageKeys[1]] = this.totalSize
      }
      if (isReset) {
        page[this.pageKeys[0]] = this.pageNo = 1
        page[this.pageKeys[1]] = this.pageSize
      }
      // console.log(page)
      if (!this.disabledLoading) this.innerLoading = true
      try {
        let res = await this.request(page)
        if (res?.code === this.SUCCESS_CODE || res?.code === '0') {
          if (callback) {
            if (res?.data?.length) {
              let filterData = this.filterData?.(res.data) ?? res.data
              this.isEportIndex && filterData.map((item, index) => item.index = index + 1)
              callback(filterData)
              return (this.innerLoading = false)
            } else if (res?.data?.list.length) {
              let filterData = this.filterData?.(res.data.list) ?? res.data.list
              this.isEportIndex && filterData.map((item, index) => item.index = index + 1)
              callback(filterData)
              return (this.innerLoading = false)
            }
            return
          }
          this.tableData = Array.isArray(res?.data) ? res.data : res?.data?.list
          if (!this.pageKeys[2]) {
            this.totalSize = res['totalSize'] || (Array.isArray(res?.data) ? res['total'] : res.data['total'])
          } else {
            if (!Array.isArray(res?.data) && !res[this.pageKeys[2]]) {
              this.totalSize = res.data[this.pageKeys[2]]
            } else {
              this.totalSize = res[this.pageKeys[2]]
            }
          }

          // console.log(this.totalSize, this.pageKeys)
        }
      } finally {
        this.innerLoading = false
      }
    },
    async getAllData() {
      return new Promise(async resolve => {
        let page = {}
        page[this.pageKeys[0]] = 1
        page[this.pageKeys[1]] = this.totalSize
        this.loadingExport = true
        let res = await this.request(page)
        this.loadingExport = false
        // console.log(res)
        if (res.code === 200) {
          resolve(res.data)
        } else {
          resolve([])
        }
      })
    },
    loadData() {
      this.getData(null, true, true)
    },
    refresh(flag = true) {
      this.getData(null, flag, true)
    },
    /*
     * 翻页或者改变页数，就更新pageNo和pageSize
     * */
    onShowSizeChange(current, size) {
      this.pageSize = size
      this.pageNo = current
      this.getData()
    },
    /*
     * 选中行
     * */
    onSelectChange(selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRowsMap.set(this.pageNo, selectedRows)
      if (this.selectConfig.type === 'radio') {
        this.$emit('row-click', null, selectedRows[0])
      } else {
        this.$emit('select-click', { rows: this.selectedRows(), keys: this.selectedRowKeys })
      }
      // console.log('onSelectChange',this.selectedRows())
    },
    /*导出表头*/
    exportHeader() {
      this.$refs.exportSelect.setDataAndGenerate([{}])
    },
    /*
     * 选择需要导出的数据
     * */
    exportSelect() {
      this.loadingExport = true
      if (this.selectedRows().length > 0) {
        if (this.$listeners['exportSelect']) {
          this.loadingExport = false
          return this.$emit('exportSelect', this.selectedRows())
        }
        let selectedRows = this.filterData?.(this.selectedRows()) ?? this.selectedRows()
        this.$refs.exportSelect.setDataAndGenerate(selectedRows)
        this.loadingExport = false
      } else {
        this.$message.warning('请选择需要导出的数据')
      }
    },
    /*
     * 导出所有的数据
     * */
    async exportAll() {
      // 参数：查询条件、导出的回调
      if (this.totalSize) {
        if (this.$listeners['exportAll']) {
          return this.$emit('exportAll', await this.getAllData())
        }
        if (this.$listeners['exportAllNoRequest']) {
          return this.$emit('exportAllNoRequest')
        }
        this.loadingExport = true
        this.getData(this.$refs.exportAll.setDataAndGenerate, false, false, false)
        setTimeout(() => {
          this.loadingExport = false
        }, 1500)
      } else {
        this.$message.warning('没有可导出的数据')
      }
    },
    /*
     * 行选中
     * */
    rowClick(event, record) {
      if (record.disabled) return
      if (this.selectConfig.use && this.$listeners['row-click']) {
        if (this.selectConfig.rowKey === undefined) {
          this.selectConfig.rowKey = 'id'
        }
        if (this.selectConfig.type === 'checkbox') {
          let resIndex = this.selectedRowKeys.findIndex(v => v === record[this.selectConfig.rowKey])
          if (resIndex !== -1) {
            this.selectedRowKeys.splice(resIndex, 1)
          } else {
            this.selectedRowKeys.push(record[this.selectConfig.rowKey])
          }

          let pageNoRows = this.selectedRowsMap.get(this.pageNo)
          if (pageNoRows) {
            let resIndex2 = pageNoRows.findIndex(v => v.id === record[this.selectConfig.rowKey])
            if (resIndex2 !== -1) {
              pageNoRows.splice(resIndex2, 1)
            } else {
              pageNoRows.push(record)
            }
            this.selectedRowsMap.set(this.pageNo, pageNoRows)
          } else {
            this.selectedRowsMap.set(this.pageNo, [record])
          }
        } else {
          this.selectedRowKeys = [record[this.selectConfig.rowKey]]
          // this.selectedRows = [record]
        }
        this.$emit('row-click', event, record)
      }

      this.$emit('select-click', { rows: this.selectedRows(), keys: this.selectedRowKeys })
    },
    selectedRows() {
      let temp = []
      for (const values of this.selectedRowsMap.values()) {
        temp = temp.concat(values)
      }
      this.isEportIndex && temp.map((item, index) => item.index = index + 1)
      return temp
    },
    clearSelected() {
      this.selectedRowsMap.clear()
      this.selectedRowKeys = []
    }
  },
  mounted() {
    this.$nextTick(() => {
      setTimeout(() => {
        if (window.getComputedStyle) {
          // 解决操作栏 缺0.5像素的问题
          const ele = document.querySelector('.ant-table-fixed .ant-table-thead tr')
          const fixedEle = document.querySelector(".ant-table-fixed-right .ant-table-thead tr")
          if (ele && fixedEle) {
            fixedEle.style.height = window.getComputedStyle(ele, null).height
          }
        }

        //解决固定操作栏差1像素问题
        const fixEle = document.querySelector('.ant-table-fixed-right')
        if (fixEle) {
          fixEle.style.width = '169px'
        }
      }, 100)
    })
    //如果不需要导出功能，那就不要初始化
    if (this.exportConfig.use) {
      const columns = this.exportConfig.customColumns // 需要导出的自定义表头，不存在则使用默认
      // console.log(columns)
      this.$refs.exportSelect.tableToExcelFile(columns ? { columns } : this.$refs.table, this.startIndex)
      this.$refs.exportAll.tableToExcelFile(columns ? { columns } : this.$refs.table, this.startIndex)
      this.selectConfig.use = true
      this.selectConfig.type = 'checkbox'
    }
    let fixedColumns = this.columns.length && this.columns[this.columns.length - 1],
      fixedColumnsArr = ['operation', 'actions', 'action', 'operator']
    if (fixedColumns.title.trim() == '操作' && fixedColumnsArr.includes(fixedColumns.dataIndex)) {
      if (!fixedColumns.fixed && this.filterColumn.length > 1 && this.isFixedRight) {
        fixedColumns.fixed = "right";
        fixedColumns.align = 'left';
      } else {
        fixedColumns.align = 'left';
      }
    }

    //没有默认选中
    let getsColumnData = JSON.parse(localStorage.getItem('dynamicColumn')) || [];
    let path = this.$route.path;
    let checked = getsColumnData.filter(item => {
      return item.path === path && item.name === this.request.name;
    })
    //是否加透明列
    if (this.isHideFixed && checked.length == 0) {
      this.filterColumn.push(
        { title: '', dataIndex: 'isHideFixed', fixed: 'right', },
      )
    }

    // console.log('mounted-----------BBBBBBBBBBBBBBB-table的Path', this.pathName)
    // 监听详情页返回刷新列表
    this.$bus.$on('handleRefresh' + this.pathName, () => {
      // console.log('--------------------BBBBBBBBBBBBBBB-table收到了，刷新刷新刷新----------------', this.pathName)
      this.getData();
    })

    // 遍历columns 更改每一项的宽度值
    //  !this.isEmptyWidth && this.$props.columns.map(item => {
    //   if((typeof item.width === 'string' && parseInt(item.width) >= 120) || (typeof item.width === 'number' && item.width >= 120)){
    //     item.width = 'auto';
    //   }
    //   item.ellipsis = false;
    // })


    // 遍历columns 更改每一项的宽度值
    !this.isEmptyWidth && this.$props.columns.map(item => {
      item.width =item.width?item.width: 'auto';
      item.ellipsis = false;
    })

    this.setColumnAttribute();
  },
  beforeDestroy() {
    // console.log('beforeDestroy-------BBBBBBBBBBBBBBB-table的Path', this.pathName)
    this.$bus.$off('handleRefresh' + this.pathName)
  },
  render(createElement, context) {
    //操作栏，slot="prefix",slot="suffix",exportConfig.use = true任意一个存在的时候，就会显示
    //三个都不传就是一个纯表格，带翻页的
    let tableOperator = ''
    if (this.$scopedSlots.prefix || this.exportConfig.use || this.$scopedSlots.suffix || this.statisticsConfig.use) {
      //导出功能
      let actionBtn = (
        <div>
          {this.$scopedSlots.prefix && this.$scopedSlots.prefix(this)}
          {this.delFunc && !this.disabled ? (
            <a-button
              type="danger"
              disabled={this.selectedRowKeys?.length === 0}
              onClick={() => this.delete(this.delFunc)}
            >
              删除行
            </a-button>
          ) : (
            ''
          )}
          {this.exportConfig.use ? (
            this.exportPermission ? (
              <span>
                <excel
                  ref="exportSelect"
                  fileName={this.exportConfig.select}
                  transformTimeKey={this.transformTimeKey}
                  is-click-generate="false"
                >
                  <a-button
                    v-btn-permission={this.exportPermission.select}
                    icon="download"
                    type="primary"
                    slot="excelBtn"
                    class="excelBtn"
                    disabled={this.selectedRowKeys?.length === 0}
                    loading={this.loadingExport}
                    onClick={this.exportSelect}
                  >
                    {this.exportConfigText.select}
                  </a-button>
                </excel>
                <excel
                  ref="exportAll"
                  fileName={this.exportConfig.all}
                  transformTimeKey={this.transformTimeKey}
                  is-click-generate="false"
                >
                  <a-button
                    v-btn-permission={this.exportPermission.all}
                    loading={this.loadingExport}
                    icon="download"
                    type="primary"
                    slot="excelBtn"
                    class="excelBtnAll"
                    onClick={this.exportAll}
                  >
                    {this.exportConfigText.all}
                  </a-button>
                </excel>
              </span>
            ) : (
              <span>
                <excel ref="exportSelect" fileName={this.exportConfig.select} is-click-generate="false">
                  <a-button
                    icon="download"
                    type="primary"
                    slot="excelBtn"
                    class="excelBtn"
                    disabled={this.selectedRowKeys?.length === 0}
                    loading={this.loadingExport}
                    onClick={this.exportSelect}
                  >
                    {this.exportConfigText.select}
                  </a-button>
                </excel>
                <excel ref="exportAll" fileName={this.exportConfig.all} is-click-generate="false">
                  <a-button
                    icon="download"
                    type="primary"
                    slot="excelBtn"
                    class="excelBtnAll"
                    loading={this.loadingExport}
                    onClick={this.exportAll}
                  >
                    {this.exportConfigText.all}
                  </a-button>
                </excel>
              </span>
            )
          ) : (
            ''
          )}
          {this.$scopedSlots.suffix && this.$scopedSlots.suffix(this)}
        </div>
      )
      let isShowCountBar = false
      if (this.selectConfig.use) isShowCountBar = true
      if (this.statisticsConfig.use) isShowCountBar = true
      if (this.isShowCountBar !== null) isShowCountBar = this.isShowCountBar
      tableOperator = (
        <div class="table-operator">
          <div class="pub-table-action-btn">{actionBtn}</div>
          {this.$scopedSlots.bottom && this.$scopedSlots.bottom()}
          {isShowCountBar && (
            <a-alert class="mb12" style="margin-top:3px" type="info" show-icon>
              <template slot="message">
                {this.selectConfig.use && <span>已选择{this.selectedRowKeys.length}项&nbsp;&nbsp;&nbsp;</span>}
                {this.isShowTotal && <span>{this.isShowTotalName}：{this.totalSize}&nbsp;&nbsp;&nbsp;</span>}
                {this.statisticsConfig.use ? (
                  this.statisticsConfig.temp ? (
                    this.statisticsConfig.temp(this.statisticsConfig.statistics)
                  ) : (
                    <span>
                      待提交审核：{this.statisticsConfig.statistics.draft || 0}， 审核中：
                      {this.statisticsConfig.statistics.submitted || 0}， 审核通过：
                      {this.statisticsConfig.statistics.past || 0}， 审核不通过：
                      {this.statisticsConfig.statistics.rejected || 0}
                      {this.isShowDeleteCount && <span>， 已作废：{this.statisticsConfig.statistics.delete || 0}</span>}
                    </span>
                  )
                ) : (
                  ''
                )}
              </template>
            </a-alert>
          )}
        </div>
      )
    }
    /*
    *
   <span>
                    &nbsp;&nbsp;&nbsp;待提交审核：{{ statistics.draft }}，
                    审核中：{{ statistics.submitted }}，
                    审核通过：{{ statistics.past }}，
                    审核不通过：{{ statistics.rejected }}，
                    已作废：{{ statistics.delete }}，
                    已变更：{{ statistics.change }}
                </span>
    *
    * */
    // if(this.$attrs['row-selection']) {
    //   this.$set(this.$attrs['row-selection'], 'fixed', true)
    // }
    return (
      <div class='tableContent'>
        {tableOperator}
        {
          this.isShowColumnFilter ? (<a-popover placement="bottomRight" v-model={this.visible} trigger="click">
            <template slot="content">
              {/* <a-table
              columns={this.checkColumns}
              data-source={this.checkColumn}
              pagination={false}
              row-selection={this.rowSelection}
              bordered
            /> */}
              <ul class="checkUl">
                <li class="thCheckbox">
                  <span class="checkedClick">
                    <a-checkbox indeterminate={this.indeterminate} checked={this.checkAll} onChange={this.onCheckAllChange} input={this.checkAll}></a-checkbox>
                  </span>
                  <span class="checkText">字段</span></li>
                {this.checkColumn.map((item, index) => {
                  return (
                    <li class="liChecked" >
                      <span class="checkedClick">
                        <input type="checkbox" checked={item.checked} value={item.checked}
                          class="customCheck"
                          key={index}
                          disabled={item.disabled}
                          onClick={($event) => this.checkedChange($event, item.value)} />
                      </span>
                      <span class="checkText">{item.value}</span></li>
                  )
                })}
              </ul>
              <div class="checkConfirm">
                <a-button onClick={this.hide} style="margin-right:10px">取消</a-button>
                <a-button onClick={this.checkChange}>确定</a-button>
              </div>
            </template>
            <a-icon type="setting" class="tableIcon a-popover-open" />
          </a-popover>) : null
        }
         {
          this.isShowTable ? (<a-popover placement="bottomRight" v-model={this.visible} trigger="click">
            <template slot="content">
              {/* <a-table
              columns={this.checkColumns}
              data-source={this.checkColumn}
              pagination={false}
              row-selection={this.rowSelection}
              bordered
            /> */}
              <ul class="checkUl">
                <li class="thCheckbox">
                  <span class="checkedClick">
                    <a-checkbox indeterminate={this.indeterminate} checked={this.checkAll} onChange={this.onCheckAllChange} input={this.checkAll}></a-checkbox>
                  </span>
                  <span class="checkText">字段</span></li>
                {this.checkColumn.map((item, index) => {
                  return (
                    <li class="liChecked" >
                      <span class="checkedClick">
                        <input type="checkbox" checked={item.checked} value={item.checked}
                          class="customCheck"
                          key={index}
                          disabled={item.disabled}
                          onClick={($event) => this.checkedChange($event, item.value)} />
                      </span>
                      <span class="checkText">{item.value}</span></li>
                  )
                })}
              </ul>
              <div class="checkConfirm">
                <a-button onClick={this.hide} style="margin-right:10px">取消</a-button>
                <a-button onClick={this.checkChange}>确定</a-button>
              </div>
            </template> 
            <a-button class="isShowTable">选择导出数据范围</a-button> 
          </a-popover>) : null
          //<a-icon type="setting"/>
        }
        <a-table
          class={['list-table', !this.isFixedRight ? 'isFixedRight' : '', this.isHideFixed ? 'isHideFixed' : '']}
          ref="table"
          row-key={this.selectConfig.rowKey}
          loading={this.innerLoading}
          dataSource={this.ArrTableData ? this.ArrTableData : this.tableData}
          props={{ ...this.$attrs, ...this.$props, columns: this.filterColumn }}
          onExpand={!!this.$listeners.expand ? this.$listeners.expand : () => { }}
          scopedSlots={{ ...this.$scopedSlots }}
          row-selection={
            this.selectConfig.use
              ? Object.assign(
                {
                  selectedRowKeys: this.selectedRowKeys,
                  type: this.selectConfig.type,
                  onChange: this.onSelectChange,
                  getCheckboxProps: record => ({
                    props: { disabled: record.disabled }
                  })
                },
                this.rowSelectionConfig
              )
              : null
          }
          // tableLayout="fixed"
          rowClassName={record => {
            return 'rowClassName'
          }}
          bordered={true}
          scroll={this.isScroll}
          pagination={false}
          customRow={record => {
            return {
              on: {
                // 事件
                click: event => {
                  this.rowClick(event, record)
                } // 点击行
              }
            }
          }}
        >
        </a-table>
        {this.showPage && (
          <a-pagination
            style={{
              display: 'flex',
              'justify-content': 'flex-end',
              margin: '10px 0'
            }}
            current={this.pageNo}
            pageSize={this.pageSize}
            pageSizeOptions={this.pageSizeOptions}
            show-quick-jumper={true}
            showSizeChanger={true}
            total={this.totalSize}
            showTotal={(total, range) => `共 ${total} 条数据`}
            onShowSizeChange={this.onShowSizeChange}
            onChange={this.onShowSizeChange}
          ></a-pagination>
        )}
      </div>
    )
  }
}
